/**
 * VimL虚拟机综合系统验证示例
 * 
 * 本示例展示了VimL虚拟机的完整功能验证，包括：
 * 1. 基本语法和变量操作
 * 2. 函数定义、调用和作用域管理
 * 3. 复杂数据结构（字典和列表）的操作
 * 4. 性能统计和监控
 * 
 * 编译和运行：
 * mkdir -p build && cd build
 * cmake .. && ninja
 * ./bin/comprehensive_system_test
 * 
 * 作者：VimL虚拟机项目组
 * 日期：2025-09-27
 */

#include "viml/compiler.h"
#include "viml/vm.h"
#include <iostream>
#include <iomanip>

using namespace viml;

// 打印测试标题的辅助函数
void print_test_header(const std::string& title) {
    std::cout << "\n" << std::string(50, '=') << std::endl;
    std::cout << " " << title << std::endl;
    std::cout << std::string(50, '=') << std::endl;
}

// 打印性能统计信息
void print_statistics(const VM::Statistics& stats, const std::string& test_name) {
    std::cout << "\n--- " << test_name << " 性能统计 ---" << std::endl;
    std::cout << std::setw(20) << "执行指令数: " << stats.instructions_executed << std::endl;
    std::cout << std::setw(20) << "函数调用数: " << stats.function_calls << std::endl;
    std::cout << std::setw(20) << "内存分配数: " << stats.memory_allocations << std::endl;
}

int main() {
    try {
        Compiler compiler;
        VM vm;
        
        print_test_header("VimL虚拟机综合系统验证");
        std::cout << "本示例将验证VimL虚拟机的核心功能模块..." << std::endl;
        
        // ========== 测试1：基本功能验证 ==========
        print_test_header("测试1：基本语法和变量操作");
        
        std::string test1 = R"(
" 基本变量赋值和输出
let x = 42
let y = "Hello VimL"
let z = 3.14

echo "整数变量 x:", x
echo "字符串变量 y:", y  
echo "浮点数变量 z:", z

" 基本算术运算
let sum = x + 10
let product = x * 2
echo "x + 10 =", sum
echo "x * 2 =", product
)";
        
        std::cout << "执行基本语法测试..." << std::endl;
        vm.reset_statistics();
        auto bytecode1 = compiler.compile(test1, "basic_syntax.vim");
        vm.execute(bytecode1);
        
        auto stats1 = vm.get_statistics();
        print_statistics(stats1, "基本语法");
        
        // ========== 测试2：函数调用和作用域 ==========
        compiler.reset();
        vm.reset();
        
        print_test_header("测试2：函数定义、调用和作用域");
        
        std::string test2 = R"(
" 定义一个计算函数
function calculate_area(length, width)
    echo "计算面积: 长度=" .. length .. ", 宽度=" .. width
    let area = length * width
    let local_message = "面积计算完成"
    echo local_message
    return area
endfunction

" 定义一个递归函数
function factorial(n)
    if n <= 1
        return 1
    else
        return n * factorial(n - 1)
    endif
endfunction

" 调用函数并测试作用域
let room_area = calculate_area(10, 8)
echo "房间面积:", room_area

let fact_5 = factorial(5)
echo "5的阶乘:", fact_5

" 测试变量作用域
let global_var = "我是全局变量"
echo global_var
)";
        
        std::cout << "执行函数和作用域测试..." << std::endl;
        vm.reset_statistics();
        auto bytecode2 = compiler.compile(test2, "functions_scope.vim");
        vm.execute(bytecode2);
        
        auto stats2 = vm.get_statistics();
        print_statistics(stats2, "函数和作用域");
        
        // ========== 测试3：复杂数据结构 ==========
        compiler.reset();
        vm.reset();
        
        print_test_header("测试3：复杂数据结构操作");
        
        std::string test3 = R"(
" 创建和操作字典
function create_student_record()
    let student = {
        "name": "张三",
        "age": 20,
        "scores": [85, 90, 78],
        "info": {"grade": "大二", "major": "计算机科学"}
    }
    return student
endfunction

" 创建学生记录
let student = create_student_record()
echo "学生姓名:", student["name"]
echo "学生年龄:", student["age"]

" 操作嵌套结构
echo "专业:", student["info"]["major"]
echo "成绩数量:", len(student["scores"])

" 计算平均分
function calculate_average(scores)
    let total = 0
    let count = len(scores)
    let i = 0
    while i < count
        let total = total + scores[i]
        let i = i + 1
    endwhile
    return total / count
endfunction

let avg_score = calculate_average(student["scores"])
echo "平均分:", avg_score

" 创建多个学生的列表
let students = []
let students = students + [student]
echo "学生列表长度:", len(students)
)";
        
        std::cout << "执行复杂数据结构测试..." << std::endl;
        vm.reset_statistics();
        auto bytecode3 = compiler.compile(test3, "data_structures.vim");
        vm.execute(bytecode3);
        
        auto stats3 = vm.get_statistics();
        print_statistics(stats3, "复杂数据结构");
        
        // ========== 系统验证总结 ==========
        print_test_header("系统验证总结");
        
        std::cout << "✓ 基本语法和变量操作：正常" << std::endl;
        std::cout << "✓ 函数定义和调用：正常" << std::endl;
        std::cout << "✓ 作用域管理：正常" << std::endl;
        std::cout << "✓ 复杂数据结构：正常" << std::endl;
        std::cout << "✓ 性能统计：正常" << std::endl;
        
        // 总体性能统计
        auto total_instructions = stats1.instructions_executed + stats2.instructions_executed + stats3.instructions_executed;
        auto total_function_calls = stats1.function_calls + stats2.function_calls + stats3.function_calls;
        auto total_memory_allocations = stats1.memory_allocations + stats2.memory_allocations + stats3.memory_allocations;
        
        std::cout << "\n--- 总体性能统计 ---" << std::endl;
        std::cout << std::setw(20) << "总执行指令数: " << total_instructions << std::endl;
        std::cout << std::setw(20) << "总函数调用数: " << total_function_calls << std::endl;
        std::cout << std::setw(20) << "总内存分配数: " << total_memory_allocations << std::endl;
        
        std::cout << "\n🎉 所有测试通过！VimL虚拟机系统运行正常！" << std::endl;
        
        return 0;
        
    } catch (const std::exception& e) {
        std::cout << "\n❌ 系统验证失败: " << e.what() << std::endl;
        std::cout << "请检查虚拟机实现或联系开发团队。" << std::endl;
        return 1;
    }
}